package Demo;

import java.util.concurrent.*;

//线程池的基本创建使用
public class Test2 {
    public static void main(String[] args) {
        //为每个线程设定时间的线程池
        ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
        for (int i = 0; i < 10; i++) {
            int number = i;
            pool.schedule(new Runnable() {
                @Override
                public void run() {
                    System.out.println("任务:"+ number);
                }
            },1,
                    //线程延迟1秒后执行
                    TimeUnit.SECONDS);
        }
    }
    public static void main3(String[] args) {
        //创建只有单个线程的线程池
        ExecutorService pool = Executors.newSingleThreadExecutor();
        for (int i = 0; i < 1000; i++) {
            int number  = i ;
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("任务:" + number);
                }
            });
        }
    }
    //动态增长的线程池
    public static void main2(String[] args) {
        ExecutorService pool = Executors.newCachedThreadPool();
        for (int i = 0; i < 10000; i++) {
            int number = i;
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("任务："+ number);
                }
            });
        }
    }
    public static void main1(String[] args) {
        //为线程池指定10个线程
        ExecutorService pool = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 1000; i++) {
            int number = i;
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("任务：" + number);
                }
            });
        }
    }
}
